package com.atguigu.service.impl;

import com.atguigu.dao.UserMapper;
import com.atguigu.pojo.User;
import com.atguigu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @ClassNAME UserServiceImpl
 * @Description
 * @Author wuyafeng atguigu
 * @Date 2021/11/11 9:30
 * @Version 1.0
 **/
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public List<User> selectAll() {
        //1.先定义key
        String key = "allUser";
        //2.先从redis中获取指定的key
        List<User> users = (List<User>)redisTemplate.boundValueOps(key).get();
        //  如果redis中存在数据， 则直接返回
        if (users != null){
            return users;
        }
        //   如果redis中没有数据， 先从DB中查询， 然后存储到redis中，最好返回
        users =  userMapper.selectAll();
        if(users!=null && users.size()>0){
            redisTemplate.boundValueOps(key).set(users);
        }
        return  users;
    }
}
